import { detailInterview, detailRegistration, registrationInfoInit, saveInterviewAudit, selectInterview } from '@/services/api/api-interview-record';
import { AudioOutlined, CarOutlined, CheckCircleOutlined, CheckCircleTwoTone, CheckOutlined, CopyOutlined, DownloadOutlined, PlusOutlined, SendOutlined, UploadOutlined, UserOutlined } from '@ant-design/icons';
import {
    ActionType,
    DrawerForm,
    ModalForm,
    ProCard,
    ProForm,
    ProFormDateRangePicker,
    ProFormInstance,
    ProFormSelect,
    ProFormText,
    ProFormTextArea,
} from '@ant-design/pro-components';
import { Alert, Button, Descriptions, Divider, Flex, Space, Spin, Tag, Typography, Upload, message, Image, DescriptionsProps, Card, Row, Col, Empty, UploadFile } from 'antd';
import { useEffect, useRef, useState } from 'react';
import EnrollMedia from './EnrollMedia';
import EnrollOrganization from './EnrollOrganization';
import { useAccess } from '@umijs/max';
import AddTravelArrangements from './AddTravelArrangements';
import TabelReports from './TabelReports';
import DetailTravelArrangements from './DetailTravelArrangements';
import { parse } from '@/utils/historyUtils';
import RegistrationInfo from './RegistrationInfo';
interface DetailsInterviewProps {
    id: string;
    title: string;
    interviewId: string;
    onRefurbish: () => void;
}

const DetailsInterview: React.FC<DetailsInterviewProps> = ({ id, title, onRefurbish, interviewId }) => {
    const access = useAccess();
    const [drawerVisit, setDrawerVisit] = useState(false);
    const formRef = useRef<ProFormInstance>();
    const [details, setDetailsState] = useState<InterviewRecordData.InterviewDetail>();
    const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewData, setPreviewData] = useState<{
        id: string;
        name: string;
        mimeType: string;
        url?: string;
    }>();
    const [previewOnlineUrl, setPreviewOnlineUrl] = useState<string>();
    const iframeRef = useRef(null);
    const [previewLoading, setPreviewLoading] = useState(true);
    const [tab, setTab] = useState('media');
    const [planTab, setPlanTab] = useState();
    const [planItems, setPlanItems] = useState();
    const [registrationInfo, setRegistrationInfo] = useState<InterviewRecordData.planList>({} as InterviewRecordData.planList);
    const [detailRegistData, setDetailRegistData] = useState<InterviewRecordData.assignOrganizationList>({} as InterviewRecordData.assignOrganizationList);
    const [reload, setReload] = useState(false)


    //获取报名信息详情
    const getDetailRegistData = async () => {
        const res = await detailRegistration({ recordId: id })
        if (res.code === 0) {
            setDetailRegistData(res.data)
        }
    }

    //获取报名信息
    const getRegistrationInfo = async () => {
        const res = await registrationInfoInit({ recordId: id })
        if (res.code === 0) {
            if (res.data.length > 0) {
                setRegistrationInfo(res.data)
            } else {
                setRegistrationInfo([])
            }
        }
    }

    /**
  * 获取 详情
  * @param key
  */
    const loadSubmitDetails = async () => {
        try {
            const response = await detailInterview({ id });
            if (response.code === 0) {
                setDetailsState(response.data)
                console.log(response.data);

                setPlanTab(response.data?.planList[0].id)
                const plan = response.data?.planList.map((item, index) => {
                    return {
                        key: item.id,
                        label: "出行安排" + (index + 1)
                    }
                })
                setPlanItems(plan)
            }

        } catch (error) { }
    };
    /**
     * 导出word
     * 
     */
    const postDownload = () => {
        fetch('https://example.com/file.pdf')
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.blob();
            })
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', 'file.pdf'); // 设置下载文件的名称
                document.body.appendChild(link);
                link.click();
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }

    useEffect(() => {
        if (interviewId === id) {
            if (interviewId !== undefined) {
                setDrawerVisit(true);
            }
        }
    }, [])


    return (
        <>
            <DrawerForm
                onOpenChange={(visible) => {
                    if (visible) {

                        loadSubmitDetails()
                        getDetailRegistData()
                        getRegistrationInfo()
                    } else {
                        onRefurbish()
                    }
                    setDrawerVisit(visible)
                }}
                title={<div style={{ display: 'flex', justifyContent: 'space-between' }}>

                    <span>{title}</span>
                    {/* <DetailTravelArrangements detail={details} /> */}
                    <Button type='primary' icon={<UploadOutlined />}>导出word</Button>
                </div>}
                open={drawerVisit}
                onFinish={async () => {
                    message.success('提交成功');
                    return true;
                }}
                drawerProps={{
                    width: "75%"
                }}
                trigger={<a>{title}</a>}

                submitter={{
                    render: (props, defaultDoms) => {
                        return [
                            access.采访要素匹配x管理员 && <AddTravelArrangements
                                onRefurbish={() => { loadSubmitDetails(), getRegistrationInfo() }}
                                // planList={registrationInfo as InterviewRecordData.planList}
                                planList={details?.planList as InterviewRecordData.planList}
                                registrationInfo={registrationInfo}
                                // planList={[]}
                                id={String(details?.id)}
                            />,
                            (access.采访要素匹配x采访媒体 && details?.interviewState === 1) && <EnrollMedia onRefurbish={() => { setReload(!reload), getDetailRegistData() }} id={String(details?.id)} detailRegistData={detailRegistData} />,
                            (access.采访要素匹配x采访对象 && details?.interviewState === 1) && <EnrollOrganization onRefurbish={() => { setReload(!reload), getDetailRegistData() }} id={String(details?.id)} detailRegistData={detailRegistData} />
                        ];
                    },
                }}
            >
                <Row gutter={[48, 16]}>

                    <Col span={14} >
                        <Spin
                            style={{
                                textAlign: 'center',
                            }}
                            spinning={details === undefined}
                        >

                            {details !== undefined && (
                                <>
                                    {title ? (
                                        <Typography.Title
                                            copyable={{
                                                icon: [
                                                    <CopyOutlined
                                                        style={{
                                                            fontSize: '16px',
                                                        }}
                                                        key="copy-icon"
                                                    />,
                                                    <CheckOutlined
                                                        style={{
                                                            fontSize: '16px',
                                                        }}
                                                        key="copied-icon"
                                                    />,
                                                ],
                                            }}
                                            level={3}
                                            style={{ textAlign: 'center' }}
                                        >
                                            {title}

                                        </Typography.Title>
                                    ) : (
                                        <Typography.Title level={3} style={{ textAlign: 'center' }}>
                                            暂无标题
                                        </Typography.Title>
                                    )}
                                    <Flex justify={'flex-end'} align={'center'}>
                                        <Descriptions>
                                            <Descriptions.Item label="活动内容">
                                                <div style={{ display: 'flex', fontSize: 15 }}>
                                                    <div
                                                        dangerouslySetInnerHTML={{
                                                            __html: `${details?.content}`,
                                                        }}
                                                    />
                                                </div>
                                            </Descriptions.Item>
                                        </Descriptions>
                                        {/* <Typography.Paragraph
                                            copyable={{
                                                icon: [
                                                    <Tag color="#108ee9" key="copy-icon">
                                                        复制内容
                                                    </Tag>,
                                                    <CheckOutlined
                                                        style={{
                                                            fontSize: '16px',
                                                        }}
                                                        key="copied-icon"
                                                    />,
                                                ],
                                                text: async () =>
                                                    new Promise((resolve) => {
                                                        var tempDivElement = document.createElement('div');
                                                        tempDivElement.innerHTML = details?.content;
                                                        resolve(tempDivElement.textContent || tempDivElement.innerText || '');
                                                    }),
                                            }}
                                        /> */}
                                    </Flex>
                                    <Descriptions>
                                        {details?.planList && details?.planList.length > 0 && <Descriptions.Item label="报名信息">
                                            <DrawerForm
                                                trigger={<a>点击查看</a>}
                                                title="报名信息"
                                                formRef={formRef}
                                                autoFocusFirstInput
                                                drawerProps={{
                                                    maskClosable: true,
                                                    destroyOnClose: true,
                                                    width: '30%',
                                                }}
                                                open={modalFormOpen}
                                                onOpenChange={(visible) => {
                                                    if (visible) {
                                                        setReload(!reload)
                                                    }
                                                    setModalFormOpenState(visible)
                                                }}
                                                submitTimeout={2000}
                                                submitter={false}

                                            >
                                                <RegistrationInfo id={details.id} reload={reload} />
                                            </DrawerForm>
                                        </Descriptions.Item>}
                                    </Descriptions>
                                    <Descriptions>
                                        <Descriptions.Item label="截止时间">{details?.deadlineTime}</Descriptions.Item>
                                    </Descriptions>

                                    {/* style={{display:'flex',justifyContent:'flex-end'}} */}

                                    {details?.attachments && details?.attachments.length > 0 && (
                                        <>
                                            <div
                                                style={{
                                                    textAlign: 'right',
                                                }}
                                            >
                                                <Button
                                                    type="primary"
                                                    key="import"
                                                    size="small"
                                                    icon={<DownloadOutlined />}
                                                    onClick={() => {
                                                        details?.attachments.forEach(function (item) {
                                                            window.open(item.content, '_blank');
                                                        });
                                                    }}
                                                >
                                                    全部下载
                                                </Button>
                                            </div>

                                            <Upload
                                                listType="picture"
                                                multiple
                                                fileList={details?.attachments.map((item) => {
                                                    return {
                                                        uid: item.id,
                                                        name: item.name,
                                                        url: item.content,
                                                        mimeType: item.mimeType,
                                                        status: 'done',
                                                    };
                                                })}
                                                showUploadList={{
                                                    downloadIcon: (
                                                        <div style={{ marginLeft: '-100px', padding: '17px 0', marginTop: '-15px' }}>
                                                            <DownloadOutlined
                                                                style={{
                                                                    marginRight: '10px',
                                                                }}
                                                            />
                                                            点击下载
                                                        </div>
                                                    ),
                                                    showRemoveIcon: false,
                                                    showDownloadIcon: true,
                                                }}
                                                onPreview={async (file: UploadFile) => {
                                                    setPreviewData({
                                                        id: file.uid,
                                                        name: file.name,
                                                        mimeType: file.mimeType,
                                                        url: encodeURI(file.url),
                                                    });
                                                    setPreviewOpen(true);
                                                }}
                                            />
                                            <DrawerForm
                                                title={previewData?.name}
                                                drawerProps={{
                                                    width: 900,
                                                    destroyOnClose: true,
                                                }}
                                                open={previewOpen}
                                                onOpenChange={async (visible) => {
                                                    if (visible) {
                                                        if (
                                                            previewData?.mimeType !== null &&
                                                            previewData?.mimeType?.indexOf('image') > -1
                                                        ) {
                                                            //图片预览
                                                        } else {
                                                            setPreviewLoading(true);

                                                            // const response = await cuesAttachmentPreview({
                                                            //     id: previewData?.id,
                                                            // });

                                                            // if (response.code === 0) {
                                                            //     setPreviewOnlineUrl(response.data);
                                                            // } else {
                                                            //     message.error('暂时无法预览');
                                                            //     setPreviewLoading(false);
                                                            // }
                                                        }
                                                    } else {
                                                        setPreviewOpen(false);
                                                        setPreviewData(undefined);
                                                        setPreviewOnlineUrl(undefined);
                                                    }
                                                }}
                                                submitter={{
                                                    searchConfig: {
                                                        submitText: '下载',
                                                    },
                                                }}
                                                onFinish={async (values) => {
                                                    window.open(previewData?.url, '_blank');
                                                }}
                                            >
                                                <Alert
                                                    style={{
                                                        marginBottom: 20,
                                                    }}
                                                    message="部分文件系统可能暂不支持在线预览，建议下载到本地"
                                                    type="warning"
                                                    showIcon
                                                />
                                                {previewData?.mimeType !== null &&
                                                    previewData?.mimeType?.indexOf('image') > -1 ? (
                                                    <Image width="100%" src={previewData?.url} />
                                                ) : (
                                                    <Spin spinning={previewLoading}>
                                                        <iframe
                                                            ref={iframeRef}
                                                            src={previewOnlineUrl}
                                                            height={200}
                                                            width="100%"
                                                            frameBorder="0"
                                                            // scrolling="false"
                                                            allowFullScreen={true}
                                                        // scrolling={'no'}
                                                        />
                                                    </Spin>
                                                )}
                                            </DrawerForm>
                                        </>
                                    )}
                                </>
                            )}
                            {Array.isArray(details?.planList) && details?.planList.length === 0 && <ProCard title="报名信息" ghost>
                                <RegistrationInfo id={details.id} reload={reload} />
                            </ProCard>}

                            {Array.isArray(details?.planList) && details?.planList.length > 0 && <div style={{ display: 'flex', paddingBlock: 20 }}>
                                <ProCard
                                    tabs={{
                                        activeKey: planTab,
                                        items: planItems,
                                        onChange: (key) => {
                                            setPlanTab(key);
                                        },
                                        tabPosition: 'left'
                                    }}
                                />

                                {details?.planList.map((item) => {

                                    //   {item.id === planTab &&}  
                                    return item.id === planTab && <div style={{ display: 'flex', flexDirection: 'column' }}>
                                        <Descriptions style={{ paddingInline: 10 }} column={2}>
                                            <Descriptions.Item label="带队人员">{item.leader}</Descriptions.Item>
                                            <Descriptions.Item label="联系电话">{item?.phone}</Descriptions.Item>
                                            <Descriptions.Item label="集中采访时间">{item?.travelTime}</Descriptions.Item>
                                            <Descriptions.Item label="采访地点">{item?.address}</Descriptions.Item>
                                            <Descriptions.Item label="发布会时间">{item?.presentationTime}</Descriptions.Item>
                                            {/* <Descriptions.Item ><Button type='primary' size='small'>编辑</Button></Descriptions.Item> */}
                                        </Descriptions>
                                        <ProCard
                                            tabs={{
                                                activeKey: tab,
                                                items: [
                                                    {
                                                        label: <span ><AudioOutlined style={{ marginRight: 5 }} />媒体信息</span>,
                                                        key: 'media',
                                                    },
                                                    {
                                                        label: <span ><UserOutlined style={{ marginRight: 5 }} />采访对象</span>,
                                                        key: 'organization',
                                                    },
                                                    {
                                                        label: <span ><CarOutlined style={{ marginRight: 5 }} />车辆安排</span>,
                                                        key: 'cars',
                                                    },
                                                ],
                                                onChange: (key) => {
                                                    setTab(key);
                                                },
                                            }}
                                        />
                                        {tab === 'cars' && <Card bordered title={<><CarOutlined style={{ marginRight: 5 }} />车辆安排</>} style={{ marginTop: -20, overflow: 'auto', maxHeight: '500px', scrollbarWidth: 'none' }}>
                                            {(Array.isArray(item?.carsList) && item?.carsList.length > 0) ? <Descriptions column={3}>
                                                {item?.carsList?.map((item) => <>
                                                    <Descriptions.Item label="车牌号">
                                                        {item?.number}
                                                    </Descriptions.Item>
                                                    <Descriptions.Item label="司机">
                                                        {item?.name}
                                                    </Descriptions.Item>
                                                    <Descriptions.Item label="电话">
                                                        {item?.phone}
                                                    </Descriptions.Item>
                                                </>)}
                                            </Descriptions> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}

                                        </Card>}
                                        {tab === 'media' && <div style={{ marginTop: -20, overflow: 'auto', maxHeight: '500px', scrollbarWidth: 'none' }}>
                                            {item?.mediaList?.map((item) =>
                                                <ProCard bordered headerBordered collapsible defaultCollapsed title={item?.mediaName} style={{ marginBottom: 10 }} >
                                                    <Descriptions column={2}>
                                                        {item.reporterList.map((item1) => <>
                                                            <Descriptions.Item label="记者">
                                                                {item1?.name}
                                                            </Descriptions.Item>
                                                            <Descriptions.Item label="电话">
                                                                {item1?.phone}
                                                            </Descriptions.Item></>
                                                        )}
                                                    </Descriptions>
                                                </ProCard>
                                            )}
                                            {(Array.isArray(item?.mediaList) && item?.mediaList.length > 0) ? <></> : <Card bordered title={<><AudioOutlined style={{ marginRight: 5 }} />媒体信息</>}><Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /></Card>}
                                        </div>}
                                        {tab === 'organization' && <div style={{ marginTop: -20, overflow: 'auto', maxHeight: '450px', scrollbarWidth: 'none' }}>
                                            {item?.assignOrganizationList?.map((item) =>
                                                <>
                                                    <ProCard bordered headerBordered collapsible defaultCollapsed title={item?.organizationName} style={{ marginBottom: 10 }}>
                                                        <Descriptions column={2} >
                                                            {item?.organizationList?.map((item) => <>
                                                                <Descriptions.Item label="联络人">
                                                                    {item?.name}
                                                                </Descriptions.Item>
                                                                <Descriptions.Item label="电话">
                                                                    {item?.phone}
                                                                </Descriptions.Item>

                                                            </>
                                                            )}

                                                        </Descriptions>
                                                        {item?.attachments && item?.attachments.length > 0 && <div style={{ marginBlock: 10 }}>
                                                            <span style={{ color: '#8c8c8c' }}>相关素材:</span>
                                                            <>
                                                                <Upload
                                                                    listType="picture"
                                                                    multiple
                                                                    fileList={item?.attachments.map((item) => {
                                                                        return {
                                                                            uid: item.id,
                                                                            name: item.name,
                                                                            url: item.content,
                                                                            mimeType: item.mimeType,
                                                                            status: 'done',
                                                                        };
                                                                    })}
                                                                    showUploadList={{
                                                                        downloadIcon: (
                                                                            <div style={{ marginLeft: '-100px', padding: '17px 0', marginTop: '-15px' }}>
                                                                                <DownloadOutlined
                                                                                    style={{
                                                                                        marginRight: '10px',
                                                                                    }}
                                                                                />
                                                                                点击下载
                                                                            </div>
                                                                        ),
                                                                        showRemoveIcon: false,
                                                                        showDownloadIcon: true,
                                                                    }}
                                                                    onPreview={async (file: UploadFile) => {
                                                                        setPreviewData({
                                                                            id: file.uid,
                                                                            name: file.name,
                                                                            mimeType: file.mimeType,
                                                                            url: encodeURI(file.url),
                                                                        });
                                                                        setPreviewOpen(true);
                                                                    }}
                                                                />
                                                                <DrawerForm
                                                                    title={previewData?.name}
                                                                    drawerProps={{
                                                                        width: 900,
                                                                        destroyOnClose: true,
                                                                    }}
                                                                    open={previewOpen}
                                                                    onOpenChange={async (visible) => {
                                                                        if (visible) {
                                                                            if (
                                                                                previewData?.mimeType !== null &&
                                                                                previewData?.mimeType?.indexOf('image') > -1
                                                                            ) {
                                                                                //图片预览
                                                                            } else {
                                                                                setPreviewLoading(true);

                                                                                // const response = await cuesAttachmentPreview({
                                                                                //     id: previewData?.id,
                                                                                // });

                                                                                // if (response.code === 0) {
                                                                                //     setPreviewOnlineUrl(response.data);
                                                                                // } else {
                                                                                //     message.error('暂时无法预览');
                                                                                //     setPreviewLoading(false);
                                                                                // }
                                                                            }
                                                                        } else {
                                                                            setPreviewOpen(false);
                                                                            setPreviewData(undefined);
                                                                            setPreviewOnlineUrl(undefined);
                                                                        }
                                                                    }}
                                                                    submitter={{
                                                                        searchConfig: {
                                                                            submitText: '下载',
                                                                        },
                                                                    }}
                                                                    onFinish={async (values) => {
                                                                        window.open(previewData?.url, '_blank');
                                                                    }}
                                                                >
                                                                    <Alert
                                                                        style={{
                                                                            marginBottom: 20,
                                                                        }}
                                                                        message="部分文件系统可能暂不支持在线预览，建议下载到本地"
                                                                        type="warning"
                                                                        showIcon
                                                                    />
                                                                    {previewData?.mimeType !== null &&
                                                                        previewData?.mimeType?.indexOf('image') > -1 ? (
                                                                        <Image width="100%" src={previewData?.url} />
                                                                    ) : (
                                                                        <Spin spinning={previewLoading}>
                                                                            <iframe
                                                                                ref={iframeRef}
                                                                                src={previewOnlineUrl}
                                                                                height={200}
                                                                                width="100%"
                                                                                frameBorder="0"
                                                                                // scrolling="false"
                                                                                allowFullScreen={true}
                                                                            // scrolling={'no'}
                                                                            />
                                                                        </Spin>
                                                                    )}
                                                                </DrawerForm>
                                                            </>
                                                        </div>}
                                                    </ProCard>
                                                </>
                                            )}
                                            {(Array.isArray(item?.assignOrganizationList) && item?.assignOrganizationList.length > 0) ? <></> : <Card bordered title={<><UserOutlined style={{ marginRight: 5 }} />采访对象</>}><Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /></Card>}
                                        </div>}
                                    </div>
                                }
                                )}
                            </div>}
                        </Spin>
                    </Col>

                    <Col span={10} >
                        <Spin
                            style={{
                                textAlign: 'center',
                            }}
                            spinning={details === undefined}
                        >
                            <TabelReports id={id} title={title} />
                        </Spin>
                    </Col>
                </Row>

            </DrawerForm >
        </>
    );
};
export default DetailsInterview;